package org.linlinjava.litemall.db.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.linlinjava.litemall.db.dao.AgedmallStoreGoodsMapper;
import org.linlinjava.litemall.db.dao.AgedmallSubscribeToInformMapper;
import org.linlinjava.litemall.db.dao.app.AppGoodsMapper;
import org.linlinjava.litemall.db.domain.AgedmallStoreGoods;
import org.linlinjava.litemall.db.domain.AgedmallStoreGoodsExample;
import org.linlinjava.litemall.db.domain.AgedmallSubscribeToInform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wj
 * @date 2022/1/4 14:18
 */
@Component
public class WechatUtil {
    private Logger logger = LoggerFactory.getLogger(WechatUtil.class);
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private EnvironmentConstant environmentConstant;

    @Resource
    private AppGoodsMapper appGoodsMapper;

    @Resource
    private AgedmallSubscribeToInformMapper agedmallSubscribeToInformMapper;

    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;

    /**
     * 获取微信小程序token
     *
     * @return
     */
    public String getWechatAccessToken() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("grant_type", "client_credential");
        paramMap.put("appid", WechatConstant.MINI_WECHAT_APP_ID);
        paramMap.put("secret", WechatConstant.MINI_WECHAT_APP_SECRET);
        String accessTokenResult = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", paramMap);
        JSONObject jsonObject = JSONObject.parseObject(accessTokenResult);
        String token = (String) jsonObject.get("access_token");
        if (StrUtil.isNotBlank(token)) {
            stringRedisTemplate.opsForValue().set("enterprise-mini-wechat-access-token", token, 7100, TimeUnit.SECONDS);
        }
        return token;
    }


    public String getWeChatUrlLink() {
        String redisUrl = stringRedisTemplate.opsForValue().get("enterprise-mini-wechat-link-url");
        if (StrUtil.isNotBlank(redisUrl)) {
            return redisUrl;
        }
        String token = stringRedisTemplate.opsForValue().get("enterprise-mini-wechat-access-token");
        if (StrUtil.isBlank(token)) {
            token = getWechatAccessToken();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expire_type", 1);
        jsonObject.put("expire_interval", 1);
        //版本 正式版为"release"，体验版为"trial"，开发版为"develop"
        jsonObject.put("env_version", environmentConstant.getEnv().equals("online") ? "release" : "trial");
        String result = cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + token
                , jsonObject.toJSONString());
        JSONObject jsonResult = JSONObject.parseObject(result);
        String url = (String) jsonResult.get("url_link");
        String urls = "https://www.baidu.com";
        if (StrUtil.isNotBlank(url)) {
            urls = url.replaceAll("\\\\", "");
        }

        if (!urls.equals("https://www.baidu.com")) {
            stringRedisTemplate.opsForValue().set("enterprise-mini-wechat-link-url", urls, 23, TimeUnit.HOURS);
        }
        return urls;
    }


    /**
     * 发送订阅的有货通知
     *
     * @return
     */
    public String sendSubscribeMessage(Long storeId, Long goodsId, Long skuId, int size) {
        logger.info("发送有货通知：{},{},{},{}", storeId, goodsId, skuId, size);
        AgedmallStoreGoodsExample storeGoodsExample = new AgedmallStoreGoodsExample();
        storeGoodsExample.createCriteria().andDeletedEqualTo(false).andStoreIdEqualTo(storeId).
                andGoodsIdEqualTo(goodsId);
        AgedmallStoreGoods storeGoods = agedmallStoreGoodsMapper.selectOneByExample(storeGoodsExample);
        if (ObjectUtil.isNotNull(storeGoods)) {
            List<AgedmallSubscribeToInform> haveSubscribeNoticeList = appGoodsMapper.getHaveSubscribeNotice(storeGoods.getId(), skuId);
            if (haveSubscribeNoticeList.size() <= size) {
                size = haveSubscribeNoticeList.size();
            }
            for (int i = 0; i < size; i++) {
                AgedmallSubscribeToInform agedmallSubscribeToInform = haveSubscribeNoticeList.get(i);
                String token = stringRedisTemplate.opsForValue().get("enterprise-mini-wechat-access-token");
                if (StrUtil.isBlank(token)) {
                    token = getWechatAccessToken();
                }
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("touser", agedmallSubscribeToInform.getUserOpenId());
                objectMap.put("template_id", agedmallSubscribeToInform.getTemplateId());
                objectMap.put("page", agedmallSubscribeToInform.getPageUrl());
                objectMap.put("data", JSON.parseObject(agedmallSubscribeToInform.getTemplateData()));
//        跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
                objectMap.put("miniprogram_state", environmentConstant.getEnv().equals("online") ? "formal" : "trial");
                String result = cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token
                        , JSON.toJSONString(objectMap));
                JSONObject jsonResult = JSONObject.parseObject(result);
                logger.info("发送订阅通知：数据param：{}", JSON.toJSONString(objectMap));
                logger.info("发送订阅通知：{}", jsonResult);
                Integer code = (Integer) jsonResult.get("errcode");
                if (code != 0) {
                    String errMsg = (String) jsonResult.get("errmsg");
                    logger.info("发送订阅通知错误：{},{}", code, errMsg);
                    return errMsg;
                } else {
                    //TODO 修改发送状态
                    agedmallSubscribeToInform.setSendFlag(1);
                    agedmallSubscribeToInformMapper.updateByPrimaryKey(agedmallSubscribeToInform);
                }
            }
        }
        return null;
    }


}
